/**
 * 存储工具类
 */

/**
 * LocalStorage 封装
 */
export class LocalStorage {
    /**
     * 设置值
     * @param key 键
     * @param value 值
     */
    static set(key: string, value: any): void {
        try {
            const serializedValue = JSON.stringify(value)
            localStorage.setItem(key, serializedValue)
        } catch (error) {
            console.error('LocalStorage set error:', error)
        }
    }

    /**
     * 获取值
     * @param key 键
     * @param defaultValue 默认值
     * @returns 值
     */
    static get<T>(key: string, defaultValue?: T): T | null {
        try {
            const item = localStorage.getItem(key)
            if (item === null) {
                return defaultValue || null
            }
            return JSON.parse(item)
        } catch (error) {
            console.error('LocalStorage get error:', error)
            return defaultValue || null
        }
    }

    /**
     * 移除值
     * @param key 键
     */
    static remove(key: string): void {
        try {
            localStorage.removeItem(key)
        } catch (error) {
            console.error('LocalStorage remove error:', error)
        }
    }

    /**
     * 清空所有
     */
    static clear(): void {
        try {
            localStorage.clear()
        } catch (error) {
            console.error('LocalStorage clear error:', error)
        }
    }

    /**
     * 检查键是否存在
     * @param key 键
     * @returns 是否存在
     */
    static has(key: string): boolean {
        try {
            return localStorage.getItem(key) !== null
        } catch (error) {
            console.error('LocalStorage has error:', error)
            return false
        }
    }

    /**
     * 获取所有键
     * @returns 键数组
     */
    static keys(): string[] {
        try {
            return Object.keys(localStorage)
        } catch (error) {
            console.error('LocalStorage keys error:', error)
            return []
        }
    }

    /**
     * 获取存储大小
     * @returns 存储大小（字节）
     */
    static size(): number {
        try {
            let size = 0
            for (const key in localStorage) {
                if (localStorage.hasOwnProperty(key)) {
                    size += localStorage[key].length + key.length
                }
            }
            return size
        } catch (error) {
            console.error('LocalStorage size error:', error)
            return 0
        }
    }

    // 获取缓存JSON
    static getJson(key: string) {
        const content = window.localStorage.getItem(key)
        if (!content) {
            return null
        }
        return JSON.parse(content)
    }

}

/**
 * SessionStorage 封装
 */
export class SessionStorage {
    /**
     * 设置值
     * @param key 键
     * @param value 值
     */
    static set(key: string, value: any): void {
        try {
            const serializedValue = JSON.stringify(value)
            sessionStorage.setItem(key, serializedValue)
        } catch (error) {
            console.error('SessionStorage set error:', error)
        }
    }

    /**
     * 获取值
     * @param key 键
     * @param defaultValue 默认值
     * @returns 值
     */
    static get<T>(key: string, defaultValue?: T): T | null {
        try {
            const item = sessionStorage.getItem(key)
            if (item === null) {
                return defaultValue || null
            }
            return JSON.parse(item)
        } catch (error) {
            console.error('SessionStorage get error:', error)
            return defaultValue || null
        }
    }

    /**
     * 移除值
     * @param key 键
     */
    static remove(key: string): void {
        try {
            sessionStorage.removeItem(key)
        } catch (error) {
            console.error('SessionStorage remove error:', error)
        }
    }

    /**
     * 清空所有
     */
    static clear(): void {
        try {
            sessionStorage.clear()
        } catch (error) {
            console.error('SessionStorage clear error:', error)
        }
    }

    /**
     * 检查键是否存在
     * @param key 键
     * @returns 是否存在
     */
    static has(key: string): boolean {
        try {
            return sessionStorage.getItem(key) !== null
        } catch (error) {
            console.error('SessionStorage has error:', error)
            return false
        }
    }

    /**
     * 获取所有键
     * @returns 键数组
     */
    static keys(): string[] {
        try {
            return Object.keys(sessionStorage)
        } catch (error) {
            console.error('SessionStorage keys error:', error)
            return []
        }
    }

    /**
     * 获取存储大小
     * @returns 存储大小（字节）
     */
    static size(): number {
        try {
            let size = 0
            for (const key in sessionStorage) {
                if (sessionStorage.hasOwnProperty(key)) {
                    size += sessionStorage[key].length + key.length
                }
            }
            return size
        } catch (error) {
            console.error('SessionStorage size error:', error)
            return 0
        }
    }
}

/**
 * Cookie 封装
 */
export class Cookie {
    /**
     * 设置Cookie
     * @param name 名称
     * @param value 值
     * @param days 过期天数
     * @param path 路径
     * @param domain 域名
     * @param secure 是否安全
     */
    static set(
        name: string,
        value: string,
        days: number = 7,
        path: string = '/',
        domain?: string,
        secure: boolean = false
    ): void {
        try {
            let expires = ''
            if (days) {
                const date = new Date()
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
                expires = '; expires=' + date.toUTCString()
            }

            let cookieString = name + '=' + encodeURIComponent(value) + expires + '; path=' + path

            if (domain) {
                cookieString += '; domain=' + domain
            }

            if (secure) {
                cookieString += '; secure'
            }

            document.cookie = cookieString
        } catch (error) {
            console.error('Cookie set error:', error)
        }
    }

    /**
     * 获取Cookie
     * @param name 名称
     * @returns 值
     */
    static get(name: string): string | null {
        try {
            const nameEQ = name + '='
            const ca = document.cookie.split(';')

            for (let i = 0; i < ca.length; i++) {
                let c = ca[i]
                while (c.charAt(0) === ' ') {
                    c = c.substring(1, c.length)
                }
                if (c.indexOf(nameEQ) === 0) {
                    return decodeURIComponent(c.substring(nameEQ.length, c.length))
                }
            }
            return null
        } catch (error) {
            console.error('Cookie get error:', error)
            return null
        }
    }

    /**
     * 移除Cookie
     * @param name 名称
     * @param path 路径
     * @param domain 域名
     */
    static remove(name: string, path: string = '/', domain?: string): void {
        try {
            this.set(name, '', -1, path, domain)
        } catch (error) {
            console.error('Cookie remove error:', error)
        }
    }

    /**
     * 检查Cookie是否存在
     * @param name 名称
     * @returns 是否存在
     */
    static has(name: string): boolean {
        return this.get(name) !== null
    }
}
